import axios from "axios";
import { ElMessage } from "element-plus";
import { getToken } from "./cookie";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8"

const service = axios.create({
    baseURL: "/dev-api",
    timeout: 5000,
})

//request响应拦截器，类似Java后端的请求拦截器，request拦截器会在后端返回请求到前端之前进行拦截
service.interceptors.response.use(
    (res) => {
        const code = res.data.code;
        const msg = res.data.msg;
        if (code != 1000) {
            ElMessage({
                message: msg,
                type: "warning",
            })
            return Promise.reject(new Error(msg));
        }else {
            //直接将后端返回的数据返回回来，res是对后端返回的数据进行包装之后的结果
            return Promise.resolve(res.data);
        }
    },
    (error) => {
        return Promise.reject(error);
    }
)

service.interceptors.request.use(
    (config) => {
        if (getToken()) {
            config.headers["Authorization"] = "Bearer " + getToken();
        }
        return config;
    },
    (error) => {
        console.log(error);
        Promise.reject(error);
    }
)

export default service